<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 应用
 *
 */
class App extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		$this->load->model('usermodel');
		$this->uid = $this->usermodel->get_id_by_token($this->input->post('token'));
		$this->load->model('appmodel');
		$this->comment_type = array(1,2);//点评类型：1 对应用的点评， 2 对专辑的点评
	}
	
	function index()
	{
		$this->myapps();
	}
	
	/**
	 * 应用列表
	 *
	 */
	function myapps()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$apps = $this->appmodel->get_apps($this->uid);
		if(count($apps) > 0){
			//输出最终的xml
			echo $this->xmllib->get_xml($apps, array('app'), 'apps');
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 查看别人的应用列表
	 *
	 */
	function other_myapps()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$uid = $this->input->post('uid');
		$apps = $this->appmodel->get_apps($uid);
		if(count($apps) > 0){
			//输出最终的xml
			echo $this->xmllib->get_xml($apps, array('app'), 'apps');
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 获取具体应用信息
	 *
	 */
	function appinfo()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$appid = $this->input->post('appid');
		$appinfo = $this->appmodel->get_app($appid);
		if($appinfo){
			//输出最终的xml
			echo $this->xmllib->get_xml($appinfo, array('app'));
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 分享大厅
	 *
	 */
	function sharelist()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$apps = $this->appmodel->get_apps_shared(1);
		if(count($apps) > 0){
			foreach ($apps as &$app) {
				unset($app['install'], $app['share'], $app['sharedtime'], $app['lastupdate']);
			}
			//输出最终的xml
			echo $this->xmllib->get_xml($apps, array('app'), 'apps');
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 分享应用
	 *
	 */
	function shareapps()
	{
		//加载表单验证类库
  		$this->load->library('form_validation');
  		
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['appid_list'] = isset($_POST['appid_list']) ? $_POST['appid_list'] : '';//此处设置时为了防止生成xml报错
		
		//_list 均是由半角逗号分隔开的
		$this->form_validation->set_rules('appid_list', '要分享的应用', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('uid_list', '', 'trim|xss_clean');
		$this->form_validation->set_rules('content', '点评内容', 'trim|max_length[140]|xss_clean');
		$this->form_validation->set_message('required', '请选择%s');
		$this->form_validation->set_message('max_length', '%s字数不要超过 %d');
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			$appid_list_error = form_error('appid_list');
			echo $this->xmllib->error_xml($appid_list_error);
			exit;
		}
		
		$appid_arr = explode(',', trim($this->input->post('appid_list'), ','));
		//$uid_arr = explode(',', trim($this->input->post('uid_list'), ','));
		//过滤数据
		//$appid_arr = array_flip($appid_arr);
		///$appid_arr = array_flip($appid_arr);
		$appid_arr = array_unique($appid_arr);
		
		//$uid_arr = array_flip($uid_arr);
		//$uid_arr = array_flip($uid_arr);
		
		//分享理由（点评内容）
		$content = $this->input->post('content');
		
		//检测提交的应用是不是属于当前用户自己所有的
		//加载comment model
		$this->load->model('commentmodel');
		$this->load->model('activemodel');
		foreach ($appid_arr as $k=>$appid){
			if(empty($appid) || !$this->appmodel->check_app($appid, $this->uid) || $this->appmodel->check_app_shared($appid)){ 
				unset($appid_arr[$k]);//去除无效的
				continue;
			}
			//设置应用的状态为 以分享 
			$this->appmodel->set_app_shared($appid);
			//将点评插入点评表中
			$content !== '' && $this->commentmodel->insert_comment(array('comment_type'		=> APP_COMMENT,
																		'comment_id'		=> $appid,
																		'uid'				=> $this->uid,
																		'content'			=> $content,
																		'share_or_comment'	=> IS_SHARE));
			//添加动态
			$this->activemodel->insert_active(array('uid' 			=> $this->uid,
													'active_id'		=> $appid,
													'active_type'	=> APP_ACTIVE,
													'memo'			=> '分享了'));
		}
		
		if(count($appid_arr) == 0){
			//没有有效的可分享的应用
			echo $this->xmllib->error_xml('要分享的应用无效或已被分享，请重新设置');
			exit;
		}
		
		/*$appcount = count($appid_arr);
		//给好友发送消息
		$this->load->model('messagesmodel');
		foreach ($uid_arr as $k=>$uid){
			if(empty($uid) || $uid==$this->uid){ //此处要加上个判断用户是不是当前用户的好友，稍候实现
				unset($uid_arr[$k]);//去除无效的
				continue;
			}
			//添加消息
			$this->messagesmodel->insert_message(array('uid' => $this->uid, 
														'fanid' => $uid, 
														'msg' => "您的好友[$_SESSION[name]]分享了 $appcount 个应用，快去看看吧！"));
		}*/
		
		//分享成功提示
		echo $this->xmllib->success_xml('您的应用分享成功');
		exit;
	}
	
	/**
	 * 添加我的应用
	 *
	 */
	function addapp()
	{
		//加载表单验证类库
  		$this->load->library('form_validation');
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['name'] = isset($_POST['name']) ? $_POST['name'] : '';//此处设置时为了防止生成xml报错
		$this->form_validation->set_rules('name', '应用名称', 'trim|required');
		$this->form_validation->set_rules('package_name', '应用包名', 'trim|required');
		//$this->form_validation->set_rules('photo', '应用图像', 'trim|required');
		$this->form_validation->set_message('required', '%s不能为空');
		
		$photo = isset($_FILES['photo']) ? $_FILES['photo'] : array();
		/*if(empty($photo) || $photo['size']==0 || empty($photo['name'])){
			echo $this->xmllib->error_xml('缺少应用图片');
			exit;
		}先去除必须要图片的限制*/
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			$name_error 	= form_error('name');
			$package_name_error = form_error('package_name');
			//$photo_error = form_error('photo');
			//显示错误信息
			if($name_error)
				echo $this->xmllib->error_xml($name_error);
			elseif($package_name_error)
				echo $this->xmllib->error_xml($package_name_error);
			//elseif ($photo_error)
				//echo $this->xmllib->error_xml($photo_error);
			exit;
		}else{
			$name = $this->input->post('name');
			//$photo = $this->input->post('photo');
			$version = $this->input->post('version');
			$install = $this->input->post('install');
			
			$package_name = $this->input->post('package_name');//应用包名，用于下载
			
			//查询添加的应用是否已经存在
			if($this->appmodel->check_app_by_name($this->uid, $name, $version)){
				echo $this->xmllib->error_xml('此同名的应用已经存在');
				exit;
			}
			
			//执行插入
			if($this->appmodel->insert_app(array('uid' 			=> $this->uid, 
													'name' 		=> $name,
													'package_name' 	=> $package_name,
													'version'	=> $version ? $version : '',
													'install'	=> $install ? $install : 0))
													){
				//得到appid
				$app = $this->appmodel->get_app_by_name($this->uid, $name, $version);
				//添加动态
				$this->load->model('activemodel');
				$this->activemodel->insert_active(array('uid' 			=> $this->uid,
														'active_id'		=> $app[0]['id'],
														'active_type'	=> APP_ACTIVE,
														'memo'			=> '安装了'));
				//存在图片上传
				if(isset($photo['size']) && $photo['size'] > 0){				
					//执行成功，则上传图片	
					//$app_info = $this->appmodel->get_app_by_name($this->uid, $name, $version);
					$appid = $app[0]['id'];
					//加载图片上传处理类库
					$this->load->library('uploadimglib');
					//加载配置文件
					$this->config->load('upload');
					$this->config->load('image_lib');
					//从配置文件中取值
					$upload_config = $this->config->item('default_img');
					$image_config = $this->config->item('default_img_resize');
					
					//做点改动，设置图片的上传路径
					$upload_config['upload_path'] = $this->uid . '/appimg';
					
					if($path = $this->uploadimglib->upload_image($upload_config, 'photo', $upload_config['default_path'])){
						if($dest_path = $this->uploadimglib->resize_image($image_config, $path)){
							//处理路径，只要相对路径即可
							$dest_path = substr($dest_path, strpos($dest_path, 'images/'.$this->uid));
							//$app = $this->appmodel->get_app($appid);
							if($this->appmodel->update_photo($appid, $dest_path)){
								////更新图像成功
								////图像处理成功，删除硬盘上原始图片
								//此时还没有原始图片
								//$this->uploadimglib->remove_image($app[0]['photo'], 1, $upload_config['default_path']); 
								//unset($app);
							}else{
								//更新图像失败
								//处理失败就删除上传成功的图片
								$this->uploadimglib->remove_image($dest_path, 1, $upload_config['default_path']);
							}
						}else{
							//resize图像失败
							//处理失败就删除上传成功的图片
							$this->uploadimglib->remove_image($dest_path, 0, $upload_config['default_path']);
						}
					}else{
						//更新图像失败
						//echo $this->xmllib->error_xml('图像更新失败，请稍候再试');
						//exit;
					}
				}
				
				echo $this->xmllib->success_xml('添加应用成功');
				exit;
			}else{
				echo $this->xmllib->error_xml('添加应用失败，请稍候再试');
				exit;
			}
		}
	}
	
	/**
	 * 比对app
	 *
	 */
	function compapps()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$app_list = $this->input->post('app_list');
		if(!$app_list){
			//为空
			echo $this->xmllib->error_xml('请选择有效的应用');
			exit;
		}
		//app_list 组合 name|version,name|version,....
		//拆分
		$app1 = @explode(',', trim($app_list, ','));
		//查询数据库中当前用户已有的应用
		$apps = $this->appmodel->get_apps($this->uid);
		foreach ($app1 as $k=>$n_v){
			foreach ($apps as $app){
				$name_version = $app['name'].'|'.$app['version'];
				if($name_version == $n_v){
					//匹配
					unset($app1[$k]);
				}
			}
		}
		
		//返回需要添加的应用
		$un_app = @implode(',', $app1);
		echo $this->xmllib->success_xml($un_app);
		exit;
	}
	
	/**
	 * 应用评论
	 *
	 */
	function commentapp()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		//加载表单验证类库
  		$this->load->library('form_validation');
		$_POST['appid'] = isset($_POST['appid']) ? $_POST['appid'] : '';//此处设置时为了防止生成xml报错
		$this->form_validation->set_rules('appid', '要点评的应用', 'required');
		$this->form_validation->set_rules('content', '点评内容', 'trim|required|max_length[140]|xss_clean');
		$this->form_validation->set_message('required', '%s不能为空');
		$this->form_validation->set_message('max_length', '%s字数不要超过 %d');
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			//错误提示
			$appid_error = form_error('appid');
			$content_error = form_error('content');
			if($appid_error)
				echo $this->xmllib->error_xml($appid_error);
			elseif ($content_error)
				echo $this->xmllib->error_xml($content_error);
			exit;
		}else{
			//验证通过
			$appid = $this->input->post('appid');
			$content = $this->input->post('content');
			//查询要评论的应用是否存在
			$this->load->model('appmodel');
			if(!$this->appmodel->check_app($appid)){
				//此应用不存在
				echo $this->xmllib->error_xml('您要评论的应用不存在');
				exit;
			}
			//添加评论信息
			$this->load->model('commentmodel');
			$data = array('comment_id' 		=> $appid, 
						  'comment_type'	=> APP_COMMENT,
						  'uid' 			=> $this->uid, 
						  'content' 		=> $content,
						  'share_or_comment'=> IS_COMMENT);
			if($this->commentmodel->insert_comment($data)){
				//添加至动态
				$this->load->model('activemodel');
				$this->activemodel->insert_active(array('uid' 			=> $this->uid,
														'active_id'		=> $appid,
														'active_type'	=> APP_ACTIVE,
														'memo'			=> '评论了'));
				
				echo $this->xmllib->success_xml('评论添加成功');
				exit;
			}else{
				echo $this->xmllib->error_xml('评论失败，请稍候再试');
				exit;
			}
		}
	}
	
	/**
	 * 获得指定应用的评论信息
	 *
	 */
	function appcomments()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$appid = $this->input->post('appid');
		$this->load->model('commentmodel');
		$comments = $this->commentmodel->get_comments_by_type($appid, APP_COMMENT);
		if($comments){
			echo $this->xmllib->get_xml($comments, array('comment'), 'comments');
			exit;
		}else{
			//为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 此应用使用的用户
	 *
	 */
	function appusers()
	{
	 	header('Content-type:text/xml');// 向浏览器输出 xml
		$appname = $this->input->post('appname');
		$users = $this->_get_user_by_appname($appname);

		if($users){
			//加载处理图片路径类库
    		$this->load->library('uploadimglib');
			//设置photo路径
			foreach ($users as $k=>$v){
				$users[$k]['photo'] = $this->uploadimglib->re_user_photo($v['photo'], $v['reg_type']);
				unset($users[$k]['reg_type']);//客户端不需要此字段
			}
			
			echo $this->xmllib->get_xml($users, array('user'), 'users');
			exit;
		}else{
			//为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 分享之星
	 *
	 */
	function mostshare()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$result = array();
		$this->db->select('u.id, u.name, u.photo, u.reg_type, count(*) as appcount')
				 ->from('user as u')
				 ->join('app as a', 'u.id=a.uid')
				 ->where(array('a.share' => 1))
				 ->group_by('u.id')
				 ->order_by('appcount', 'desc')
				 ->limit(20);
		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			//如果有结果集
			$this->load->library('uploadimglib');
			$result = $query->result_array();
			//设置photo路径
			foreach ($result as $k=>$v){
				$result[$k]['photo'] = $this->uploadimglib->re_user_photo($v['photo'], $v['reg_type']);
				unset($result[$k]['reg_type']);//不需要此字段
			}
		}
		if(count($result) > 0){
			echo $this->xmllib->get_xml($result, array('user'), 'users');
			exit;
		}else{
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 人气最旺
	 *
	 */
	function popularapp()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$this->db->select('a.name, a.id, a.photo, count(*) as share_count')
				 ->from('app as a')
				 ->where(array('a.share' => 1))
				 ->group_by('a.name')
				 ->order_by('a.name')
				 ->limit(20);
		$query = $this->db->get();
		if($query->num_rows() > 0){
			$this->load->library('uploadimglib');//处理图片路径
			$result = $query->result_array();
			//去查找对应的收藏数量
			foreach ($result as $k=>$v){
				$this->db->select('count(*) count')
						 ->from('collection as c')
						 ->join('app as a', 'a.id=c.collection_id and c.collection_type=' . APP_COLLECTION)
						 ->where('a.name', $v['name']);
				$query = $this->db->get();
				$row = $query->row_array();
				$result[$k]['collection_count'] = $row['count'];
				$result[$k]['photo'] = $this->uploadimglib->re_image_path($v['photo']);
			}
			echo $this->xmllib->get_xml($result, array('app'), 'apps');
			exit;
		}else{
			//为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 下载排行
	 *
	 */
	function mostdownload()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$result = array();
		$this->db->select('a.id, a.name, a.photo, count(*) as download_times')
				 ->from('app as a')
				 ->where(array('a.install' => 1))
				 ->group_by('a.name')
				 ->order_by('download_times', 'desc')
				 ->limit(20);
		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			//如果有结果集
			$this->load->library('uploadimglib');
			$result = $query->result_array();
			//设置photo路径
			foreach ($result as $k=>$v){
				$result[$k]['photo'] = $this->uploadimglib->re_image_path($v['photo']);
			}
		}
		if(count($result) > 0){
			echo $this->xmllib->get_xml($result, array('app'), 'apps');
			exit;
		}else{
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	//根据应用名称取得使用此应用的用户
	function _get_user_by_appname($name='')
	{
		//设置分页
		$this->dblib->set_query_limit();
		//查询
		$this->db->select('distinct(u.id), u.name, u.photo, u.reg_type')
				 ->from('user as u')
				 ->join('app as a', 'u.id=a.uid')
				 ->where(array('a.name' => $name))
				 ->order_by('a.lastupdate', 'desc');
		$query = $this->db->get();
		$users = $query->result_array();
		return $users;
	}
}


/* End of file app.php */
/* Location: ./application/controllers/app.php */